package main.service;

import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.MessageLite;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


/**
 * 消息体管理类
 * 通过配置或者程序注入的方式 根据 moduleid和actionid以及二进制协议可以得到对应的消息体
 * @author King
 *
 */
public class PBMessageManager
{
	
	private static final Logger log = LoggerFactory.getLogger(PBMessageManager.class);
	
	private Map<Integer, MessageLite> messageMap = new HashMap<>();

	public MessageLite getMessage(int messageId, byte[] body)
	{
		try {
			MessageLite messageLite  = messageMap.get(messageId);
			if(messageLite==null)
				return null;
			return messageLite.newBuilderForType().mergeFrom(body).build();
		} catch (InvalidProtocolBufferException e) {
			log.error("",e);
			e.printStackTrace();
		}
		return null;
	}


	public void addMessageCla(int messageId,  Class<? extends GeneratedMessageV3> msgCla) {
		try {
			if(msgCla==null)
				return;
			Method method = msgCla.getMethod("getDefaultInstance");
			MessageLite lite = (MessageLite)method.invoke(null, null);
			messageMap.put(messageId, lite);
		} catch (Throwable e) {
			log.error("",e);
			e.printStackTrace();
		}
	}

}
